package com.o2opuzi.lib.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author yue han jiang
 * @date 2015年3月6日
 * @file_name DigestUtils.java
 */
public class DigestUtils extends org.apache.commons.codec.digest.DigestUtils{
	
	private static final Log LOG = LogFactory.getLog(DateUtils.class);
	
	private static final String ENCRYPT_TYPE_AES = "AES";
	
	private static final String AES_KEY = "MQyVUmEfSdNMFdYn";
	
	/**
	 * AES 加密
	 * @param key
	 * @param value
	 * @return
	 */
	public static byte[] encryptAES(String key,byte[] value){
		try {
			SecretKey secretKey = new SecretKeySpec(key.getBytes(),ENCRYPT_TYPE_AES);
			SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), ENCRYPT_TYPE_AES);
			Cipher cipher = Cipher.getInstance(ENCRYPT_TYPE_AES);
			cipher.init(Cipher.ENCRYPT_MODE, keySpec);
			return cipher.doFinal(value);
		} catch (Exception e) {
			if(LOG.isDebugEnabled())
				LOG.error("AES 加密失败"+e.getMessage(), e);
		}
		return null;
	}
	
	public static byte[] encryptAES(byte[] value){
		return encryptAES(AES_KEY, value);
	}
	
	
	/**
	 * AES 解密
	 * @param key
	 * @param value
	 * @return
	 */
	public static byte[] dencryptAES(String key,byte[] value){
		try {
			SecretKey secretKey = new SecretKeySpec(key.getBytes(),ENCRYPT_TYPE_AES);
			SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(),ENCRYPT_TYPE_AES);
			Cipher cipher = Cipher.getInstance(ENCRYPT_TYPE_AES);
			cipher.init(Cipher.DECRYPT_MODE, keySpec);
			return cipher.doFinal(value);
		} catch (Exception e) {
			if(LOG.isDebugEnabled())
				LOG.error("AES 加密失败"+e.getMessage(), e);
		}
		return null;
	}
	
	public static byte[] dencryptAES(byte[] value){
		try {
			SecretKey secretKey = new SecretKeySpec(AES_KEY.getBytes(),ENCRYPT_TYPE_AES);
			SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(),ENCRYPT_TYPE_AES);
			Cipher cipher = Cipher.getInstance(ENCRYPT_TYPE_AES);
			cipher.init(Cipher.DECRYPT_MODE, keySpec);
			return cipher.doFinal(value);
		} catch (Exception e) {
			if(LOG.isDebugEnabled())
				LOG.error("AES 加密失败"+e.getMessage(), e);
		}
		return null;
	}
}
